import axios from 'axios'
import { ElMessage } from 'element-plus'
import config from './config'
import { parseParams } from '../urlUtils'
import { showLoading, hideLoading } from '../loadingUtils'
// import qs from 'qs'

// 创建axios实例
const request = axios.create({
  baseURL: config.baseUrl, // api 的 base_url
  timeout: config.requestTimeout, // 请求超时时间
  headers: config.defaultHeaders // 请求头
})

let token // token

// request拦截器
request.interceptors.request.use(
  (config) => {
    if (!(config.headers && config.headers.ignoreLoading)) {
      showLoading()
    }
    /* if (
        config.method === 'post' &&
        (config.headers['Content-Type'] === 'application/x-www-form-urlencoded')) {
          config.data = qs.stringify(config.data)
      }*/
    // get参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        if (config.params[key] !== void 0 && config.params[key] !== null) {
          url += `${key}=${encodeURIComponent(config.params[key])}&`
        }
      }
      url = url.substring(0, url.length - 1)
      config.params = {}
      config.url = url
    }
    // 格式化form-data参数
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = parseParams(config.data)
    }
    // 注入token
    // if (!token) {
    // }
    token = localStorage.getItem('token')
    if (token) {
      Object.assign(config.headers, { 'X-Access-Token': token })
      Object.assign(config.headers, { 'Authorization': token })
    }
    return config
  },
  (error) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
request.interceptors.response.use(
  (response) => {
    // 延迟关闭loading，避免同步请求多次出现loading
    setTimeout(() => {
      closeLoading()
    }, 100)
    if (response && response.data && (response.data.code === 500 || response.data.code === 506)) {
      ElMessage.error(response.data.errorMsg.content)
      return response
    }
    // 登出时清空token
    if (response.config.url === '/sys/logout') {
      token = null
    }
    if (response && response.data && response.data.code === 400) {
      ElMessage.error(response.data.message)
    }
    if (response && response.data && response.data.code === 401) {
      localStorage.removeItem('loginUser')
      localStorage.removeItem('token')
      token = null
      window.location.href = '#/login'
    }
    if (response && response.data && response.data.code === 403) {
      ElMessage.error('Access Denied!')
    }
    if (response.config.responseType === 'blob') {
      // 如果是文件流，直接过
      return response
    } else if (response.data.success) {
      return response.data
    } else {
      // ElMessage.error(response.data.message || response.data.errorMsg.content)
      return response.data
    }
  },
  (error) => {
    // 延迟关闭loading，避免同步请求多次出现loading
    setTimeout(() => {
      closeLoading()
    }, 100)
    return Promise.reject(error)
  }
)

/**
 *  关闭loading
 */
function closeLoading () {
  hideLoading()
}

export default request
